<?php
class Showtime_model extends CI_Model {

	function getAll()
	{
		$query = $this->db->get('showtime');
		return $query->result('Showtime');
	}  
	
	//get value on schedule page, after user clicks on buy
	function get($id)
	{
		$msg = "select s.id as 'id', m.title as 'title', th.name as 'name',
				th.address as 'address', s.date as 'date', s.time as 'time',
				s.available as 'available'
			from movie m, theater th, showtime s
			where s.movie_id = m.id and s.theater_id = th.id and s.id = '$id'";
		$query = $this->db->query($msg);
		
		return $query->row();
	}
	
	function delete($id) {
		return $this->db->delete('showtime', array('id' => $id));
	}
	
	function insert($movie_id, $theater_id, $date, $time, $available) {
		return $this->db->insert('ticket', 
				array('movie_id' => $movie_id,
					  'theater_id' => $theater_id,
					  'date' => $date,
					  'time' => $time,
					  'available' => $available));
	}
	
	function update_availability($showtime){
		$msg = "UPDATE showtime SET available = available - 1 WHERE id = $showtime"; 
		$query = $this->db->query($msg);		
	}
	
	function update($showtime) {
		$this->db->where('id', $showtime->id);
		return $this->db->update('showtime', 
				array('movie_id' => $showtime->movie_id,
					  'theater_id' => $showtime->theater_id,
					  'date' => $showtime->date,
					  'time' => $showtime->time,
					  'available' => $showtime->available));
	}
	
	function get_showtimes($info) {
		$movie = $info['movie'];
		$theater = explode(" - ", $info['theater']);
		$date = explode(" - ", $info['date']);
		
		$msg = "select s.id as 'id', m.title as 'title', th.name as 'name',
				th.address as 'address', s.date as 'date', s.time as 'time',
				s.available as 'available'
			from movie m, theater th, showtime s 
			where s.movie_id = m.id and s.theater_id = th.id and 
				s.date > curdate() and s.available > 0";
		
		if(strcasecmp($info['movie'], "All") != 0) {
			$msg = $msg . " and m.title = '$movie'";
		}
		
		if(strcasecmp($info['theater'], "All") != 0) {
			$msg = $msg . " and th.name = '$theater[0]' and th.address = '$theater[1]'";
		}
		
		if(strcasecmp($info['date'], "All") != 0) {
			$msg = $msg . " and s.date = '$date[0]' and s.time = '$date[1]'";
		}
		
		$query = $this->db->query($msg);
		return $query;
	}
	
	function show_showtimes() {
		return $this->db->query("select date, time from showtime where date > curdate()");
	}
}